// pages/pay/pay.js
var common = require("../../utils/public.js") //引入public.js脚本
const api = require('../../utils/api.js')
var time = require("../../utils/time.js");
import '../../utils/lodash/index.js'
import _ from '../../utils/lodash/lodash.js'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    //商品列表
    buyCarts: [],
    //金额
    totalPrice: '',
    //运费
    minAmount: '',
    //总押金
    totalDeposit: "",
    //实收金额
    truthPrice: "",
    //京币
    jb: "",
    jbShow: true,
    arr: [],
    realPrice: "",
    addrMess: {},
    payType: [],
    //线上 线下标识

    payIndex: 0,
    pickId: 1,
    //支付参数
    timeStamp: "",
    nonceStr: "",
    package: "",
    signType: "",
    paySign: "",
    showMore: false,
    color: "",
    //本地抵用
    mortgage: "",
    //订单编号
    out_trade_no: "",
    //活动
    rules: '',

    //所有优惠卷
    couponUserList: [],
    // 满减券
    couponUserList_youHui: [],
    // 运费
    couponUserList_yunFei: [],

    //券
    couponShowList: [],
    // 券类型 1满减券 2运费券
    couponType: null,
    couponListAvaliabale: [],
    couponListUnvaliabale: [],
    // 满减可用的券
    couponListAvaliabale_youHui: [],
    // 满减不可用的券
    couponListUnvaliabale_youHui: [],
    // 运费可用的券
    couponListAvaliabale_yunFei: [],
    // 运费不可用的券
    couponListUnvaliabale_yunFei: [],
    // 选中满减券
    couponActive: {},
    // 选中的免运费券
    couponActive1: {},
    // 订单商品对应的分摊价格
    discountMap: {},

    // 参加的优惠活动
    rules: [],
    // 查看的当前优惠活动
    activeRules: [],
    isType: null,
    remark: ''
  },
  //超过两个商品 点击显示全部
  show: common.throttleFunc(function (e) {
    let that = this
    let buyCarts = that.data.buyCarts
    let showMore = that.data.showMore
    if (showMore == false) {
      if (buyCarts.length > 2) {
        for (var i = 0; i < buyCarts.length; i++) {//遍历数组 给数组元素加上隐藏
          buyCarts[i].showCar = true;
        }

      } else {
        for (var i = 0; i < buyCarts.length; i++) {//遍历数组 给数组元素加上隐藏
          buyCarts[i].showCar = true;
        }
      }
      showMore = !showMore
      that.setData({
        buyCarts: buyCarts,
        showMore: showMore
      })
    } else {
      showMore = !showMore
      for (var i = 0; i < buyCarts.length; i++) {//遍历数组 给数组元素加上隐藏
        buyCarts[i].showCar = false;
      }
      buyCarts[0].showCar = true
      buyCarts[1].showCar = true
      that.setData({
        buyCarts: buyCarts,
        showMore: showMore
      })
    }

  }),
  //滑动切换
  swiperTab: function (e) {
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  //点击切换
  clickTab: function (e) {
    var that = this;
    const { current } = e.target.dataset

    if (this.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: current,
      })
    }
  },
  //选择优惠券弹出框
  select_yhq: common.throttleFunc(function (e) {
    const couponType = e.currentTarget.dataset.type
    const {couponListAvaliabale_youHui, couponListUnvaliabale_youHui, couponListAvaliabale_yunFei, couponListUnvaliabale_yunFei } = this.data
    // // 按券类型 分券
    // const currentList = couponUserList.filter(i => i.type == couponType)
    // // 分开可用券 不可用券
    // const { couponListAvaliabale, couponListUnvaliabale } = this.splitCoupon(currentList)

    let couponListAvaliabale = [], couponListUnvaliabale = []
    if(couponType == 1) {
      couponListAvaliabale = couponListAvaliabale_youHui
      couponListUnvaliabale = couponListUnvaliabale_youHui
    } else if(couponType == 2){
      couponListAvaliabale = couponListAvaliabale_yunFei
      couponListUnvaliabale = couponListUnvaliabale_yunFei
    }
    this.setData({
      currentTab: 0,
      couponType,
      couponListAvaliabale,
      couponListUnvaliabale,
      showModalStatus: 'on',
      yhqStatus: 'on'
    })
  }),

  splitCoupon(list) {
    const { buyCarts, discountMap } = this.data
    let couponListAvaliabale = [], couponListUnvaliabale = []
    const { rules } = this.data
    const now = Date.now()
    let canUseTicket = ''
    // 有活动 查活动可不可用券
    if (rules.length) {
      canUseTicket = rules.some(rule => rule.activityFullReduceUseTicket == '1')
    } else {
      // 无活动 直接查可用商品
      canUseTicket = true
    }

    list.forEach(item => {
      let goods = []
      if (item.ticketDiscountRange == 2 && item.ticketDiscountGoodsEntityList.length) {
        item.ticketDiscountGoodsEntityList.forEach(it => {
          buyCarts.forEach(good => {
            if (good.goodsDetailsId == it.goodsDetailsId) {
              goods.push(good)
            }
          })
        })
      } else {
        buyCarts.forEach(good => {
          goods.push(good)
        })
      }
      if(goods.length > 0) {
        const total = goods.reduce((acc, curr) => {
          acc += +curr.priceToShow * curr.amount - (discountMap[curr.goodsDetailsId] || 0)
          return acc
        }, 0)
        if (total.toFixed(2) >= item.minRange && canUseTicket && now < item.endDate) {
          couponListAvaliabale.push(item)
        } else {
          couponListUnvaliabale.push(item)
        }
      } else {
        couponListUnvaliabale.push(item)
      }
    })

    const maxCoupon = _.maxBy(couponListAvaliabale, o => o.amount);
    return {
      couponListAvaliabale,
      couponListUnvaliabale,
      maxCoupon: maxCoupon || {},
    }
  },

  //隐藏弹出框
  hideModal: common.throttleFunc(function (e) {
    let that = this
    wx.showModal({
      content: '是否放弃本次付款',
      cancelText: '放弃',
      confirmText: '继续付款',
      success: function (res) {
        if (res.confirm) {



        } else if (res.cancel) {
          that.setData({
            showModalStatus: '',
            yhqStatus: '',
            payStatus: ''
          }),
            wx.navigateTo({
              url: '../myOrder/myOrder?type=' + 3,
            })
        }
      }
    })

  }),
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    const carts = JSON.parse(decodeURIComponent(options.carts))
    let that = this
    let totalPrice = carts.totalPrice
    let minAmount = carts.minAmount

    let totalDeposit = carts.totalDeposit
    let buyCarts = carts.buyCarts
    let jb = carts.jb
    let rules = carts.rules
    //实收金额 和 金币余额
    if (Number(jb) > Number(totalPrice)) {
      that.setData({
        mortgage: (Number(totalPrice) + Number(minAmount) + Number(totalDeposit)).toFixed(2)
      })
    } else if (Number(jb) <= Number(totalPrice)) {
      that.setData({
        mortgage: Number(jb).toFixed(2)
      })
    }

    let totalPriceToShow = parseFloat(totalPrice)

    if(rules.length) {
      rules.forEach(i => {
        i.beginDateStr = time.formatTimeTwo(i.activityFullReduceBeginDate, 'Y-M-D')
        i.endDateStr = time.formatTimeTwo(i.activityFullReduceEndDate, 'Y-M-D')
        totalPriceToShow += +i.reduceAmount
      })
    }
    that.setData({
      buyCarts: JSON.parse(decodeURIComponent(options.carts)).buyCarts,
      jb: Number(jb).toFixed(2),
      totalPrice: Number(totalPrice).toFixed(2),
      minAmount: Number(minAmount).toFixed(2),
      oldMinAmount: Number(minAmount).toFixed(2),
      totalDeposit: Number(totalDeposit).toFixed(2),
      truthPrice: Number(Number(totalPrice) + Number(minAmount) + Number(totalDeposit)).toFixed(2),
      rules: rules,
      totalPriceToShow: totalPriceToShow.toFixed(2)
    },() => {
      that.couponUserList()
    })
    buyCarts = that.data.buyCarts
    if (buyCarts.length > 2) {
      for (var i = 0; i < buyCarts.length; i++) {//遍历数组 给数组元素加上隐藏
        buyCarts[i].showCar = false;
      }
      buyCarts[0].showCar = true
      buyCarts[1].showCar = true
    } else {
      for (var i = 0; i < buyCarts.length; i++) {//遍历数组 给数组元素加上隐藏
        buyCarts[i].showCar = true;
      }
    }
    let arr = that.data.arr
    buyCarts.forEach(v => {

      arr: arr.push({
        goodsDetailsId: v.goodsDetailsId,//商品明细ID
        amount: Number(v.amount),//数量
        goodsName: v.goodsName,//商品名称
        goodsTypeId: "",//商品类别
        spec: Number(v.detailSpec),//商品明细规格goodsTypeId
        price: Number(v.price),//单价
        receivePrice: Number(v.detailSalesPrice * v.amount),//应收金goodsTypeId额
        discountPrice: 0,//优惠金额
        depositGoodsId: v.detailDepositGoodsId,//押金商品ID
        deposit: Number(v.detailDeposit),//押金
        actualPrice: Number(v.detailSalesPrice * v.amount),//实收金额
      })
    })

    const resx = await api.getPickTypeList({})
    resx.body.getPickTypeList.forEach((item, index) => {
      item.index = index
    })
    that.setData({
      arr: arr,
      buyCarts: buyCarts,
      payType: resx.body.getPickTypeList,
      pickId: resx.body.getPickTypeList[0].pickId
    })
    that.addrs();

    
    this.fn(buyCarts)
  },

  fn(buyCarts) {
    const goodsDetailsId = buyCarts.map(good => good.goodsDetailsId)
    api.PayGetApportion({
      cityId: wx.getStorageSync("cityId"),
      goodsDetailsId
    }).then(res => {
      if (res.result) {

        const discountMap = res.body.getApportion.reduce((acc, item) => {
          acc[item.goodsDetailsId] = item.discountPrice || 0
          return acc
        }, {})
        this.setData({ discountMap })
      }
    })
  },
  //获取优惠卷列表
  couponUserList() {
    const {minAmount} = this.data
    wx.showLoading({
      icon: 'none',
      mask: true
    })
    api.couponUserList({
      cityId: wx.getStorageSync("cityId")
    }).then(res => {
      if (res.result) {
        res.body.getTicket.forEach(i => {
          i.endDateStr = time.formatTimeTwo(i.endDate, 'Y-M-D h:m')
        })
        const couponUserList = res.body.getTicket

        const couponUserList_youHui = couponUserList.filter(i => i.type == 1)
        const couponUserList_yunFei = couponUserList.filter(i => i.type == 2)
        const { couponListAvaliabale: couponListAvaliabale_youHui, couponListUnvaliabale: couponListUnvaliabale_youHui, maxCoupon: maxCounpon_youHui } = this.splitCoupon(couponUserList_youHui)
        const { couponListAvaliabale: couponListAvaliabale_yunFei, couponListUnvaliabale: couponListUnvaliabale_yunFei, maxCoupon: maxCounpon_yunFei } = this.splitCoupon(couponUserList_yunFei)
        let a = []
        if(maxCounpon_youHui.id) {
          a.push({id: maxCounpon_youHui.id, type: maxCounpon_youHui.type})
        }
        if(maxCounpon_yunFei.id) {
          a.push({id: maxCounpon_yunFei.id, type: maxCounpon_yunFei.type})
        }
        wx.hideLoading()
        this.setData({
          couponUserList,
          couponUserList_youHui,
          couponUserList_yunFei,
          couponListAvaliabale_youHui,
          couponListUnvaliabale_youHui,
          couponListAvaliabale_yunFei,
          couponListUnvaliabale_yunFei,
          couponActive: maxCounpon_youHui,
          couponActive1: minAmount > 0 ? maxCounpon_yunFei : {},
          ids: a
        }, () => {
          this.caculatePrice(a)
        })
      }
    })
  },

  //订单选择位置

  //订单选择位置
  addrs() {
    let that = this;
    api.handleAddr({
      openId: wx.getStorageSync("openId"),
      cityId: wx.getStorageSync("cityId"),
      addressType: wx.getStorageSync("type")
    })
      .then(res => {
        if (res.result) {
          if (wx.getStorageSync("type") == 2) {
            let index = res.object.findIndex((v, i) => v.flag == 1 && v.userInfoEntity.type == 2 ? v : '')
            that.setData({
              addrMess: res.object[index]
            })
          } else if (wx.getStorageSync("type") == 1 || wx.getStorageSync("type") == 0) {
            // 可用地址
            let index = res.object.findIndex((v, i) => v.status == 1 ? v : '')
            res.object.forEach((v, i) => {
              if (v.cityId == wx.getStorageSync("cityId")) {
                //城市相同
                if (v.flag == 1 && v.status == 1) {
                  //默认可用
                  that.setData({
                    addrMess: v
                  })
                } else if (v.flag == 1 && v.status == 3) {
                  //默认不可用
                  that.setData({
                    addrMess: res.object[index] //第一个可用地址
                  })
                }
              } else if (v.flag == 1 && v.cityId != wx.getStorageSync("cityId")) {
                //把其他城市的flag设为0
                v.flag = 0
              }
            })
          }
        }
      })
  },

  onShow: function () {
    this.setData({
      isType: wx.getStorageSync("type")
    })
  },

  //选择是否选择金币
  btnJb: function () {
    this.setData({
      jbShow: !this.data.jbShow,
    })
  },
  //支付类型选择
  payType: function (e) {
    let that = this
    const {ids, payType, oldMinAmount} = this.data
    let index = e.currentTarget.dataset.index
    const pickId = payType[index].pickId
    that.setData({
      payIndex: index,
      minAmount: (pickId == 3 || pickId == 4 ) ? 0.00 : oldMinAmount,
      pickId
    }, () => {
      this.caculatePrice(ids)
    })

  },
  //支付
  btnPay: function () {
    let that = this
    wx.requestPayment({
      timeStamp: this.data.timeStamp,
      nonceStr: this.data.nonceStr,
      package: this.data.package,
      signType: "MD5",
      paySign: this.data.paySign,
      success: function (res) {

        if (res.errMsg == 'requestPayment:ok') {
          //成功回调
          api.payDirect({
            orderCode: that.data.out_trade_no
          }).then(res => {
            if (res.result) {
              that.setData({
                showModalStatus: 'on',
                payStatus: 'on',
              })
              wx.navigateTo({
                url: '/pages/myOrder/myOrder?type=' + 3,
              })
            }
          })

        }
      },
      fail: function (res) {
      }
    })
  },


  //提交订单
  openPay: common.throttleFunc(function (e) {
    const {payType, payIndex} = this.data
    const pickId = payType[payIndex].pickId
    let that = this
    wx.showLoading({
      title: '加载中...'
    })
    let truthPrice = Number(that.data.truthPrice)  //应收金额
    let jb = Number(that.data.jb)  //京币
    let realPrice = that.data.realPrice  //实收金额 
    // let payIndex = that.data.payIndex //线上线下标识
    if (that.data.out_trade_no != "") {
      that.setData({
        showModalStatus: 'on',
        payStatus: 'on',
      })
    } else {
      if (pickId == 1 || pickId == 3) {
        //判断是否选中金币
        if (that.data.jbShow == false) {
          //如果京币大于等于金币
          if (jb >= truthPrice) {
            that.pay()
          } else {
            //应收金额减去金币 真实收的金额
            that.setData({
              realPrice: (truthPrice - jb).toFixed(2)
            })
            that.pay()
          }
        } else {
          that.setData({
            realPrice: truthPrice.toFixed(2)
          })
          that.pay()
        }
      } else {
        that.pay()
      }
    }
  }),


  //支付
  pay: function () {
 
    const { couponActive, couponActive1, truthPrice, addrMess, totalDeposit, minAmount, jbShow, payIndex, remark, payType } = this.data
    let that = this
    let data = {
      pickId: payType[payIndex].pickId,
      actualPrice: Number(truthPrice),
      addr: addrMess.addr,  //收货地址
      buildNo: addrMess.buildNo, //门牌号
      cityId: wx.getStorageSync('cityId'),  //城市id
      deposit: Number(totalDeposit),//总押金
      isJb: jbShow == false ? '1' : '0',
      // payType: payIndex + 1,
      payType: payType[payIndex].pickId,


      userInfoId: wx.getStorageSync('openId'),
      receivePreice: Number(truthPrice),//应收金额
      discountPrice: 0,//优惠金额
      tranPrice: Number(minAmount),//运输费用
      shopId: addrMess.shopId == null ? '' : addrMess.shopId,//店铺ID
      takePerson: addrMess.takePerson,//收货人
      linktel: addrMess.linktel,//收货人电话
      longitude: addrMess.longitude,//经度
      latitude: addrMess.latitude,//纬度
      orderDetailsEntityList: that.data.arr,
      remarks: remark,
      cityCode: addrMess.cityCode,
      cityAddr: addrMess.addr
    }
    if (couponActive.id) {
      data.ticketDiscountId = couponActive.id
    }
    if (couponActive1.id) {
      data.ticketFreightId = couponActive1.id
    }
    api.saveOrderInfo(data).then(res => {
      const { payType } = this.data
      const pickId =  payType[payIndex].pickId
      if (res.result == true) {
        //动画隐藏
        wx.hideLoading();

        // if (that.data.payIndex == '0' || that.data.payIndex == '2') {
          if (pickId == '1' || pickId == '3') {

          if (that.data.jbShow == false && Number(that.data.truthPrice) > Number(that.data.jb)) {

            if (res.code == 200) {

              that.setData({
                showModalStatus: 'on',
                payStatus: 'on',
                timeStamp: res.object.timeStamp,
                nonceStr: res.object.nonce_str,
                package: res.object.packageParams,
                signType: "MD5",
                paySign: res.object.sign,
                out_trade_no: res.object.out_trade_no,
              })
            } else {
              wx.showToast({
                title: res.object,
                icon: 'none',
                duration: 1000,
              })
            }
          } else if (that.data.jbShow == true) {
            if (res.code == 200) {
              that.setData({
                showModalStatus: 'on',
                payStatus: 'on',
                timeStamp: res.object.timeStamp,
                nonceStr: res.object.nonce_str,
                package: res.object.packageParams,
                signType: "MD5",
                paySign: res.object.sign,
                out_trade_no: res.object.out_trade_no,
              })
            } else {
              wx.showToast({
                title: res.object,
                icon: 'none',
                duration: 1000,
              })

            }


          } else if (that.data.jbShow == false && Number(that.data.truthPrice) <= Number(that.data.jb)) {

            if (res.code == 99) {
              wx.showToast({
                title: '京钱支付成功',
                icon: "none",
                duration: 1000,
                success: () => {
                  setTimeout(function () {
                    wx.navigateTo({
                      url: '/pages/myOrder/myOrder?type=' + 3,
                    })
                  }, 1000)
                }
              })
            } else {
              wx.showToast({
                title: res.object,
                icon: 'none',
                duration: 1000,
              })
            }
          }
        // } else if (that.data.payIndex == '1' || that.data.payIndex == '3') {
        } else if (pickId == '2' || pickId == '4') {
          if (res.code == 111) {
            wx.showToast({
              title: '订单提交成功',
              icon: "none",
              duration: 1000,
              success: () => {
                setTimeout(function () {
                  wx.navigateTo({
                    url: '/pages/myOrder/myOrder?type=' + 3,
                  })
                }, 1000)
              }
            })
          } else {
            wx.showToast({
              title: res.object,
              icon: 'none',
              duration: 1000,
            })
          }
        }
      } else {
        //动画隐藏
        wx.hideLoading();
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },


  butAddress: function (e) {
    if (wx.getStorageSync("type") == 1) {
      wx.navigateTo({
        url: '../address/address?type=' + 1,
      })
    } else {
      wx.navigateTo({
        url: '/pages/personAddress/personAddress?type=' + 1,
      })
    }
  },

  //显示支付方式弹出框
  openAct: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: 'on',
      actStatus: 'on'
    })
  }),

  hideModal1: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: '',
      yhqStatus: '',
      payStatus: '',
      actStatus: ''
    })
  }),

  hideModal2: common.throttleFunc(function (e) {
    this.setData({
      showModalStatus: '',
      yhqStatus: '',
      payStatus: '',
      actStatus: ''
    })
  }),

  //去详情
  details: function (e) {
    wx.navigateTo({
      url: '../detail/detail?id=' + e.currentTarget.dataset.id,
    })
  },


  //点击活动
  select_hd: common.throttleFunc(function (e) {
    const { rules } = this.data
    this.setData({
      showModalStatus: 'on',
      hdStatus: 'on',
      activeRules: [rules[e.currentTarget.dataset.index]]
    })
  }),
  //优惠劵隐藏
  hideDiscount: function () {
    this.setData({
      showModalStatus: '',
      yhqStatus: '',
      payStatus: '',
      actStatus: '',
      hdStatus: '',
    })
  },

  //优惠劵隐藏
  hideDiscount1: function () {
    const {couponType, totalPrice, minAmount, totalDeposit, couponActive, couponActive1, jb} = this.data

    let truthPrice = Number(totalPrice) + Number(minAmount) + Number(totalDeposit)
    //清除满减券
    if(couponType == 1 && couponActive1.amount){
      if(couponActive1.amount > minAmount) {
        truthPrice = truthPrice - minAmount
      } else {
        truthPrice = truthPrice - couponActive1.amount
      }
    } else if(couponType == 2 && couponActive.amount){// 清除运费券
      truthPrice = truthPrice - couponActive.amount
    }
    if(couponType == 1) {
      this.setData({
        couponActive: {}
      })
    } else {
      this.setData({
        couponActive1: {}
      })
    }
    let mortgage = truthPrice
    if(Number(jb) <= Number(truthPrice)) {
      mortgage = jb
    }
    this.setData({
      truthPrice: (+truthPrice).toFixed(2),
      mortgage: (+mortgage).toFixed(2)
    })
    this.hideDiscount()
  },

  //满减隐藏
  discount: function () {
    this.setData({
      showModalStatus: '',
      yhqStatus: '',
      payStatus: '',
      actStatus: '',
      hdStatus: ''
    })
  },
  caculatePrice(ids) {
    const { couponUserList, totalPrice, minAmount, totalDeposit, couponActive, couponActive1, jb, payIndex } = this.data
    let coupon1 = {}, coupon2 = {}, truthPrice = (Number(totalPrice) + Number(minAmount) + Number(totalDeposit)).toFixed(2), mortgage = 0
    ids.forEach(it => {
      const coupon = couponUserList.find(i => {
        return i.type == it.type && i.id == it.id
      })
      // 点击满减券计算
      if (it.type == 1) {
        coupon1 = coupon
        truthPrice = truthPrice - coupon1.amount  
      } else if (it.type == 2 && minAmount > 0) {
        coupon2 = coupon
        // 减去满减
        if (coupon2.amount) {
          if (coupon2.amount > minAmount) {
            truthPrice = truthPrice - minAmount
          } else {
            truthPrice = truthPrice - coupon2.amount
          }
        }
      }
    })

    mortgage = truthPrice
    if(Number(jb) <= Number(truthPrice)) {
      mortgage = jb
    }
    // 选中的运费券
    this.setData({
      couponActive: coupon1,
      couponActive1: coupon2,
      truthPrice: Number(truthPrice).toFixed(2),
      mortgage: Number(mortgage).toFixed(2)
    })
    this.hideDiscount()
  },

  selectCoupon(e) {
    const { current, id } = e.currentTarget.dataset
    const { couponUserList, couponType, totalPrice, minAmount, totalDeposit, couponActive, couponActive1, jb } = this.data
    if (current == 1) {
      return
    } else {
      const item = couponUserList.filter(i => {
        return i.type == couponType && i.id == id
      })

      const coupon = item[0]
      // 点击满减券计算
      if (couponType == 1) {
        let truthPrice = (Number(totalPrice) + Number(minAmount) + Number(totalDeposit) - coupon.amount).toFixed(2)
        // 减去免运费券
        if (couponActive1.amount) {
          if (couponActive1.amount > minAmount) {
            truthPrice = truthPrice - minAmount
          } else {
            truthPrice = truthPrice - couponActive1.amount
          }
        }
        let mortgage = truthPrice
        if(Number(jb) <= Number(truthPrice)) {
          mortgage = jb
        }
        // 选中的满减券
        this.setData({
          couponActive: coupon,
          truthPrice: Number(truthPrice).toFixed(2),
          mortgage: Number(mortgage).toFixed(2)
        })
      } else if (couponType == 2) {
        // 点击满运费券计算
        let truthPrice = (Number(totalPrice) + Number(minAmount) + Number(totalDeposit)).toFixed(2)
        // 减去满减
        if (coupon.amount) {
          if (coupon.amount > minAmount) {
            truthPrice = truthPrice - minAmount
          } else {
            truthPrice = truthPrice - coupon.amount
          }
        }
        truthPrice = (truthPrice - (couponActive.amount ? couponActive.amount : 0)).toFixed(2)
        let mortgage = truthPrice
        if(Number(jb) <= Number(truthPrice)) {
          mortgage = jb
        }
        // 选中的运费券
        this.setData({
          couponActive1: coupon,
          truthPrice: Number(truthPrice).toFixed(2),
          mortgage: Number(mortgage).toFixed(2)
        })
      }
      this.hideDiscount()
    }
  },
  
  toSearch(e) {
    const { ticketDiscountName, ticketDiscountId,id} = e.currentTarget.dataset.coupon
    wx.navigateTo({
      url: '/pages/searchDiscounts/searchDiscounts?id=' + ticketDiscountId + '&ticketDiscountName=' + ticketDiscountName + '&ticketId=' + ticketDiscountId,
    })
  },
  remarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  }
})